//
//  BroadcastViewController.m
//  jungoo
//
//  Created by Vu Tu Cuong on 10/8/12.
//
//

#import "BroadcastViewController.h"
#import "Extensions.h"
#import "PeopleFilterViewController.h"

@interface NSDictionary (Sorter)

- (NSComparisonResult)compare:(NSDictionary*)other;

@end

@implementation NSDictionary (Sorter)

- (NSComparisonResult)compare:(NSDictionary*)other
{
    NSInteger disOfThis = [[self objectForKey:@"distance"] integerValue];
    NSInteger disOfOther = [[other objectForKey:@"distance"] integerValue];
    
    if (disOfThis < disOfOther) {
        return NSOrderedAscending;
    }
    
    if (disOfThis > disOfOther) {
        return NSOrderedDescending;
    }
    
    return NSOrderedSame;
}

@end

@interface BroadcastViewController ()

@end

@implementation BroadcastViewController

#pragma mark - Private Method

- (void)initAppearance
{
    [self setTitle:@"Broadcast"];
    [self setBackButtonImageActiveName:@""
                          inactiveName:@"back-button"
                                target:self
                                action:@selector(back)];
    
    [self setRightButtonImageActiveName:@""
                           inactiveName:@"done-button"
                                 target:self
                                 action:@selector(done)];
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_bg.png"]]];
    
    dataSource = [NSMutableDictionary new];
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

#pragma mark - View Life

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initAppearance];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [cell0 release];
    [cell1 release];
    [cell2 release];
    [locationManager setDelegate:nil];
    [locationManager stopUpdatingLocation];
    [locationManager release];
    [super dealloc];
}

#pragma mark - Action

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)done
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if ([[dataSource objectForKey:@"message"] length] == 0) {
        [JGoUtility showAlert:@"Please enter a message!"];
        return;
    }
    
    [JGoUtility showProgressInView:[JGoUtility frontFromView:self.view]
                            target:self title:@"Broadcasting..."
                          selector:@selector(delayBroadcast:)];
}

#pragma mark - TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (indexPath.section == 1 ? 44 : 150);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 120;
    }
    
    if (section == 1) {
        return 0;
    }
    
    return 24;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UILabel *labelCircle = (id)[header0 viewWithTag:1];
        NSString *circle = [dataSource objectForKey:@"circle"];
        
        if ([circle length] == 0) {
            labelCircle.text = @"All";
        }
        else {
            
            if ([JGoUtility widthFromString:circle font:labelCircle.font] < 180) {
                CGRect newRect = labelCircle.frame;
                newRect.size.height = 21;
                labelCircle.numberOfLines = 1;
                labelCircle.frame = newRect;
            }
            else {
                CGRect newRect = labelCircle.frame;
                newRect.size.height = 42;
                labelCircle.numberOfLines = 2;
                labelCircle.frame = newRect;
            }
            
            labelCircle.text = circle;
        }

        return header0;
    }
    
    if (section == 1) {
        return nil;
    }
        
    if (section == 2) {
        return header1;
    }
    
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    
    if (section == 1) {
        return 2;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 1) {
        
        switch (indexPath.row) {
            case 0: {
                NSString *circle = [dataSource objectForKey:@"circle"];
                cell = cell0;
                cell.selectionStyle = UITableViewCellSelectionStyleGray;
                
                [cell titleTextWithTag:1].text = [circle length] ? circle : @"All";
                
                break;
            }
            case 1: {
                cell = cell1;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    
    if (indexPath.section == 2) {
        cell = cell2;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell textViewWithTag:1].text = [dataSource objectForKey:@"message"];
        [cell textViewWithTag:1].delegate = (id)self;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        PeopleFilterViewController *pfVC = [[[PeopleFilterViewController alloc] initWithNibName:@"PeopleFilterViewController"
                                                                                   bundle:nil] autorelease];
        [pfVC setDelegate:(id)self];
        [pfVC setFilterStr:[dataSource objectForKey:@"circle"]];
        [self.navigationController pushViewController:pfVC animated:YES];
    }
    else if (indexPath.section != 2) {
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
}

#pragma mark - People Filter

- (void)setupViewController:(PeopleFilterViewController *)controller didFinishSetupWithInfo:(NSString *)filterString
{
    [dataSource setValue:filterString forKey:@"circle"];
    [self.tableView reloadData];
}

#pragma mark - TextView

- (BOOL)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [dataSource setValue:textView.text forKey:@"message"];
    [self.tableView reloadData];
    
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    UITableViewCell *cell = (id)textView.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 206, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
    
    return YES;
}

- (void)delayBroadcast:(MBProgressHUD*)progress
{
    NSString *lat;
    NSString *lon;
    NSError *error = nil;
    NSString *userId = [[JGoUtility sharedCreateAccount] objectForKey:@"user_id"];
    NSArray *people = nil;
    NSString *filter = [dataSource objectForKey:@"circle"];
    
    CGFloat currentLatitude = [[locationManager location]coordinate].latitude;
    lat = [NSString stringWithFormat:@"%f",currentLatitude];
    CGFloat currentLongitude = [[locationManager location]coordinate].longitude;
    lon = [NSString stringWithFormat:@"%f",currentLongitude];
    
    filter = (filter == nil ? @"" : filter);
    
    people = [JGoAPI getPeopleWithUserId:userId
                                searchBy:@""
                                   isFav:NO
                                  filter:filter
                                     lat:lat
                                     lon:lon
                                   error:&error];
    
    people = [people sortedArrayUsingSelector:@selector(compare:)];
    
    if ([people count]) {
        
        NSMutableArray *broadcastIds = [[NSMutableArray new] autorelease];
        NSMutableArray *broadcastNames = [[NSMutableArray new] autorelease];        
        NSInteger np = ([people count] >= 4 ? 4 : [people count]);
        
        for (int ibc = 0; ibc < np; ibc++) {
            [broadcastIds addObject:[[people objectAtIndex:ibc] objectForKey:@"user_id"]];
            [broadcastNames addObject:[[people objectAtIndex:ibc] objectForKey:@"name"]];
        }
        
        NSString *textMessage = [dataSource objectForKey:@"message"];
        
        NSDictionary *newConversation = [JGoAPI createConversationWithUserId:userId
                                                            conversationName:textMessage
                                                                  inviteeIds:[broadcastIds componentsJoinedByString:@";"]
                                                                       error:&error];
        
        if (!error) {
            
            NSString *nCid = [[newConversation objectForKey:@"data"] objectForKey:@"id"];
            
            [JGoAPI addMessageWithUserId:userId
                          conversationId:nCid
                                    type:@"0"
                                 content:textMessage
                                   error:&error];
            
            if (!error) {                
                [JGoUtility showAlert:[NSString stringWithFormat:@"You just broadcast to : %@.",[broadcastNames componentsJoinedByString:@";"]]];
            }
        }
        
        if (error) {
            [JGoUtility showAlert:[error localizedDescription]];
        }
    }
    else {
        [JGoUtility showAlert:@"Can NOT found people to broadcast!"];
    }
    
    [progress hide:YES];
}

@end
